//
//  UITextField+Placeholder.m
//  coco
//
//  Created by Vill on 2023/1/3.
//

#import "UITextField+Placeholder.h"
// 导入头文件，导入下面其中一个即可
#import <objc/runtime.h>

// OC最喜欢懒加载,用的的时候才会去加载
// 需要给系统UITextField添加属性,只能使用runtime

static NSString *const LYMPlaceholderLabelKey = @"placeholderLabel";
static NSString *const placeholderColorName = @"placeholderColor";

@implementation UITextField (Placeholder)

#pragma mark - 利用RunTime动态增加属性和交换方法 =
/// 实现交换方法 （mg_setPlaceholder:和setPlaceholder:的互换）
+ (void)load{
    Method mg_setPlaceholder = class_getInstanceMethod(self, @selector(mg_setPlaceholder:));
    
    Method setPlaceholder = class_getInstanceMethod(self, @selector(setPlaceholder:));
    
    method_exchangeImplementations(setPlaceholder, mg_setPlaceholder);
}

/// 外界赋值占位颜色的时候就会调用
- (void)setPlaceholderColor:(UIColor *)placeholderColor{
    // 动态增加placeholderColor属性
    objc_setAssociatedObject(self, (__bridge const void *)(placeholderColorName), placeholderColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    // 设置颜色
   UILabel *placeholderLabel = [self valueForKeyPath:LYMPlaceholderLabelKey];
    placeholderLabel.textColor = placeholderColor;
}
- (UIColor *)placeholderColor{
    //    return  _placeholderColor;
    return objc_getAssociatedObject(self,(__bridge const void *)(placeholderColorName));
}

/// 外界赋值占位文字的时候会调用(自定义的方法，用来和系统的方法交换)
- (void)mg_setPlaceholder:(NSString *)placeholder{
    // 1.设置占位文字
    [self mg_setPlaceholder:placeholder];
   
    // 2.设置占位文字颜色
    self.placeholderColor = self.placeholderColor;
}

/// 给uitextfield添加一个清除按钮
-(void)setModifyClearButton:(NSString *)clearName{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setBackgroundImage:KImaged(clearName) forState:UIControlStateNormal];
    btn.frame = CGRectMake(10, 0, 40, 40);
    [btn addTarget:self action:@selector(clear:) forControlEvents:UIControlEventTouchUpInside];
    self.rightView = btn;
    self.rightViewMode = UITextFieldViewModeWhileEditing;
}

-(void)clear:(UIButton *)btn{
    self.text = @"";
}

@end
